class User < ActiveRecord::Base
  devise :database_authenticatable, :recoverable, :rememberable, :trackable, :registerable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :login, :password, :password_confirmation, :remember_me, :client_attributes

  has_and_belongs_to_many :roles
  has_one :client, :dependent => :destroy

  accepts_nested_attributes_for :client

  validates_uniqueness_of :login, :case_sensitive => false
  validates :login, :presence => { :message => 'Debe ingresar un nombre de usuario válido.' }, :uniqueness => { :message => 'El nombre de usuario ingresado ya existe.' }
  validates :password, :presence => { :message => 'Debe ingresar una contraseña válida.' }, :confirmation => { :message => 'Las contraseñas ingresadas no coinciden.' } #, :unless => :skip_validate_password?
  validates :password_confirmation, :presence => { :message => 'Debe ingresar la confirmación de la contraseña.' } #, :unless => :skip_validate_password?

  def role?(role)
      !!self.roles.find_by_name(role.to_s.camelize)
  end

  def orders
    self.client.orders
  end

  def client?
    role?(:client)
  end

  def admin?
    role?(:admin)
  end

  def assign_role(role_name)
    r = Role.find_by_name(role_name)
    self.roles << r
    self.save
  end
end
